//
//  RetainGuard.h
//  DiceWar
//
//  Created by xiaofeng on 27/6/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#ifndef CLASSES_GAME_UTIL_RETAINGUARD_H_
#define CLASSES_GAME_UTIL_RETAINGUARD_H_

#include "cocos2d.h"

template<typename ResourceType>
class RetainGuard
{
public:
    explicit RetainGuard(ResourceType* pResource);
    RetainGuard();
    ~RetainGuard();
    
private:
    RetainGuard(const RetainGuard& other);
    RetainGuard& operator=(const RetainGuard& other);
    
public:
    void reset(ResourceType* pResource);
    
    ResourceType* operator->();
    ResourceType* get();
    ResourceType& operator*();
    
private:
    ResourceType* m_pResource;
};

template<typename ResourceType>
RetainGuard<ResourceType>::RetainGuard()
: m_pResource(NULL) {}

template<typename ResourceType>
RetainGuard<ResourceType>::RetainGuard(ResourceType* pResource)
{
    m_pResource = pResource;
    if (m_pResource) m_pResource->retain();
}

template<typename ResourceType>
RetainGuard<ResourceType>::~RetainGuard()
{
    if (m_pResource) m_pResource->release();
}

template<typename ResourceType>
void RetainGuard<ResourceType>::reset(ResourceType* pResource)
{
    if (m_pResource) m_pResource->release();
    
    m_pResource = pResource;
    if (m_pResource) m_pResource->retain();
}

template<typename ResourceType>
ResourceType* RetainGuard<ResourceType>::operator->()
{
    return m_pResource;
}

template<typename ResourceType>
ResourceType* RetainGuard<ResourceType>::get()
{
    return m_pResource;
}

template<typename ResourceType>
ResourceType& RetainGuard<ResourceType>::operator*()
{
    return *m_pResource;
}


#endif //CLASSES_GAME_UTIL_RETAINGUARD_H_
